package algo;

import graph.GraphEdge;
import graph.GraphNode;
import io.DataReader;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import route.Route;

public class RouteAnalysis {

	/**
	 * @param args
	 */
	public static void main(String[] args) {

		int AUG = 1;

		if (args.length != 4) {
			System.out
					.println("Usage: java -jar routeAnalysis.jar <vertexFile> <edgeFile> <routeFile> NumRoutesToRead");
			System.exit(0);
		}

		String vertexFile = args[0];
		String edgeFile = args[1];
		String routesFile = args[2];
		int numRoutesToRead = Integer.parseInt(args[3]);

		System.out.println("loading vertices...");
		HashMap<Integer, GraphNode> vertices = DataReader.loadVertices(
				vertexFile, Share.initHashMapSize);
		System.out.println("loading edges...");
		HashMap<Integer, GraphEdge> edges = DataReader.loadEdges(vertices,
				edgeFile, AUG, Share.initHashMapSize);

		HashMap<Integer, Route> routes = DataReader.loadRoutes(routesFile,
				edges, numRoutesToRead);

		double[] minMaxMedian = computeMedianLength(routes);
		System.out.println("min, max, median : " + minMaxMedian[0] + ", "
				+ minMaxMedian[1] + ", " + minMaxMedian[2]);

	}

	/**
	 * 
	 * @param routes
	 * @return the min, max and median length of all routes
	 */
	static private double[] computeMedianLength(HashMap<Integer, Route> routes) {
		// compute the median length of the routes
		List<Double> routeLengths = new ArrayList<Double>(routes.size());

		for (Route r : routes.values()) {
			if (r.getLength() != 0)
				routeLengths.add(r.getLength());
		}

		Double[] lengthArr = routeLengths.toArray(new Double[0]);

		Arrays.sort(lengthArr);
		double median = 0;

		if (lengthArr.length % 2 == 0) {
			median = (lengthArr[lengthArr.length / 2 - 1] + lengthArr[lengthArr.length / 2]) / 2;
		} else {
			median = lengthArr[(lengthArr.length - 1) / 2];
		}
		double[] result = { lengthArr[0], lengthArr[lengthArr.length - 1],
				median };

		return result;
	}

}
